﻿using System;
using System.Web.Mvc;
using System.Web.Routing;

using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.ContentManagementFramework.Web.StartUp
{
    /// <summary>
    /// Provides methods for initializing CMS dependencies and services.
    /// </summary>
    public static class CmsPolicy
    {
        /// <summary>
        /// Front end area name. Used for correct render partial views and actoin.
        /// </summary>
        public static string FrontEndArea { get; set; }
       
        /// <summary>
        /// Inits CMS dependencies, services in current service locator. Registers MVC Areas.
        /// </summary>
        /// <param name="container">IUnityContainer for register.</param>
        /// <param name="options">Options: MVC Route filters, custom routes, front end area name, DataConnectResolver</param>
        /// <remarks>
        /// It clears ViewEngines collection.
        /// Adds RazorViewEngine for URL starting with '/admin'
        /// Sets an object of <see cref="CmsControllerFactory" /> as controller factory.
        /// Set ServiceLocator before use.
        /// </remarks>
        public static void Init(CmsPolicyOptions options = null)
        {
            if (DependencyServiceLocator.Current == null) 
            {
                throw new NullReferenceException("Set DependencyServiceLocator.Current before use this method");
            }

            if (options != null)
            {
                if (options.Filters != null)
                {
                    GlobalFiltersPolicy.Init(options.Filters);
                }

                if (options.Routes != null)
                {
                    RoutePolicy.Init(options.Routes);
                }

                if (!string.IsNullOrWhiteSpace(options.FrontEndArea))
                {
                    FrontEndArea = options.FrontEndArea;
                }
            }

            WebPolicy.Init(options != null ? options.DataConnectionResolver : null);
        }
    }

    /// <summary>
    /// CMS initialization options
    /// </summary>
    public class CmsPolicyOptions
    {
        /// <summary>
        /// MVC filters collection
        /// </summary>
        public GlobalFilterCollection Filters { get; set; }

        /// <summary>
        /// Custom routes to register
        /// </summary>
        public RouteCollection Routes { get; set; }

        /// <summary>
        /// Front Area name.
        /// </summary>
        public string FrontEndArea { get; set; }

        /// <summary>
        /// DataConnectorResolver. Used for specifiing different connection strings for different CMS entities.
        /// </summary>
        public Func<object, string> DataConnectionResolver { get; set; }
    }
}
